//
//  AudiovisualViewController.m
//  Alltelevisionnews
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 三人行. All rights reserved.
//

#import "SLVideoPageViewController.h"
#import "SLLoadModelFromNetWork.h"
#import "SLVideoCell.h"
#import "SLVideoCellModel.h"
#import <MediaPlayer/MediaPlayer.h>


@interface SLVideoPageViewController () <UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) NSMutableArray *modelArray;
@property (assign, nonatomic) NSInteger pageIndex;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) MBProgressHUD *hud;
@property (strong, nonatomic) MPMoviePlayerViewController *playerView;
@property (assign, nonatomic) CGRect selectRect;
@property (strong, nonatomic) NSIndexPath *indexPath;
@property (assign, nonatomic) BOOL isPlayerAtCorner;

@end

@implementation SLVideoPageViewController


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([ZDQSingleton shareSingleton].isLongin == YES) {
        self.tableView.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.3 alpha:1];
    } else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }


    [self createDrawerBtn];
    [self createRefresh];
//    [self addObserver];
    
    [self hudLoadNewData];
}


- (UITableView *)tableView
{
    if (! _tableView) {
        _tableView = [[UITableView alloc] init];
        [self.view addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 345;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    
    return _tableView;
}


- (void)createDrawerBtn
{
    // 创建左侧抽屉按钮
    UIButton *menuBtu = [UIButton buttonWithType:UIButtonTypeCustom];
    menuBtu.frame = CGRectMake(0, 0, 20, 18);
    [menuBtu setBackgroundImage:[UIImage imageNamed:@"menu"] forState:UIControlStateNormal];
    [menuBtu addTarget:self action:@selector(openOrCloseLeftList) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menuBtu];
}


- (void)createRefresh
{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self refreshAddData];
    }];
}


- (void)openOrCloseLeftList {
    
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (tempAppDelegate.leftslideVC.closed) {
        [tempAppDelegate.leftslideVC openLeftView];
    } else {
        [tempAppDelegate.leftslideVC closeLeftView];
    }
}


//- (void)addObserver
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerStopAction:) name:@"MPMoviePlayerPlaybackStateDidChangeNotification" object:self.playerView.moviePlayer];
//}


//- (void)playerStopAction:(NSNotification *)notification
//{
//    NSLog(@"notification");
//    
//    switch (self.playerView.moviePlayer.playbackState) {
//        case MPMoviePlaybackStateStopped:
//            
//            NSLog(@"MPMoviePlaybackStateStopped");
//            [self.playerView.view removeFromSuperview];
//            break;
//         
//        case MPMoviePlaybackStatePaused:
//            NSLog(@"MPMoviePlaybackStatePaused");
//            break;
//            
//        default:
//            break;
//    }
//}


- (void)playAction:(UIButton *)button
{
    if (self.playerView.view) {
        [self.playerView.view removeFromSuperview];
    }
    
    SLVideoCell *cell = (SLVideoCell *)button.superview.superview;
    self.indexPath = [self.tableView indexPathForCell:cell];
    
    SLVideoCellModel *model = self.modelArray[self.indexPath.row];
    self.playerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:model.mp4_url]];
    [cell.contentView addSubview:self.playerView.view];
    self.playerView.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
    self.playerView.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
    
    [self.playerView.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.playImageView);
    }];
    
    self.isPlayerAtCorner = NO;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SLVideoCell *cell = [SLVideoCell cellWithTableView:tableView];
    cell.model = self.modelArray[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    
    [cell.playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    SLVideoCell *cell = (SLVideoCell *)[self.tableView cellForRowAtIndexPath:self.indexPath];
    
    CGRect rectInTable = [self.tableView rectForRowAtIndexPath:self.indexPath];
    CGRect rectInSelfView = [self.tableView convertRect:rectInTable toView:self.view];
    
    if ([self.playerView.moviePlayer isPreparedToPlay]) {
        if (rectInSelfView.origin.y + cell.playImageView.frame.origin.y + cell.playImageView.frame.size.height < 0 || rectInSelfView.origin.y > self.view.size.height - CGRectGetMaxY(cell.playImageView.frame) + cell.playImageView.frame.size.height) {
            
            if (! self.isPlayerAtCorner) {
                NSLog(@"出屏");
                [self.view addSubview:self.playerView.view];
                
                self.playerView.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
                self.playerView.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
                
                [self.playerView.view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.and.right.equalTo(self.view);
                    make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.5);
                    make.height.mas_equalTo(self.view.mas_width).multipliedBy(0.5 * 9.0 / 16.0);
                }];
               
                self.isPlayerAtCorner = YES;
            }
            
            [self.view addSubview:self.playerView.view];
            
            //缩放模式
            self.playerView.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
            //控制方式
            self.playerView.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
            
            [self.playerView.view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.and.right.equalTo(self.view);
                make.width.mas_equalTo(self.view.mas_width).multipliedBy(0.5);
                make.height.mas_equalTo(self.view.mas_width).multipliedBy(0.5 * 9.0 / 16.0);
            }];
            
        } else {
            
            if (self.isPlayerAtCorner) {
                NSLog(@"入屏");
                [self.tableView addSubview:self.playerView.view];
                
                self.playerView.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
                self.playerView.moviePlayer.controlStyle = MPMovieControlStyleEmbedded;
                
                [self.playerView.view mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(self.tableView).offset(rectInTable.origin.x + cell.playImageView.x);
                    make.top.equalTo(self.tableView).offset(rectInTable.origin.y + cell.playImageView.frame.origin.y);
                    make.width.and.height.equalTo(cell.playImageView);
                }];
                
                self.isPlayerAtCorner = NO;
            }
        }
    }
}


- (void)loadNewData
{
    self.pageIndex = 0;
    [SLLoadModelFromNetWork loadModelWithIndex:self.pageIndex success:^(id modelObject) {
        NSArray *array = modelObject;
        self.modelArray = [array mutableCopy];
        
        [self.tableView reloadData];
        
        [self.hud removeFromSuperview];
        self.hud = nil;
        
        [self.tableView.mj_header endRefreshing];
        
        self.pageIndex++;
        
    } failure:^(NSError *error) {
        NSLog(@"VideoPageViewContoller ====== 获取数据失败");
        
        [self.tableView.mj_header endRefreshing];
        
    }];
}


- (void)hudLoadNewData
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"正在加载...";
    
    [self loadNewData];
}


- (void)refreshAddData
{
    [SLLoadModelFromNetWork loadModelWithIndex:self.pageIndex success:^(id modelObject) {
        NSArray *array = modelObject;
        [self.modelArray addObjectsFromArray:array];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
        
        self.pageIndex++;
    } failure:^(NSError *error) {
        NSLog(@"VideoPageViewContoller ====== 获取数据失败");
    }];
}




@end
